import json
import os
from datetime import datetime

class DataHandler:
    """
    数据处理工具类，用于管理和查询操场开放时间等数据
    """
    
    def __init__(self, data_dir=None):
        self.data_dir = data_dir or os.path.join(
            os.path.dirname(__file__), '..', 'data')
        self.open_hours_path = os.path.join(self.data_dir, 'open_hours.json')
        self.routes_path = os.path.join(self.data_dir, 'routes.json')
    
    def load_open_hours(self):
        """加载操场开放时间数据"""
        try:
            if not os.path.exists(self.open_hours_path):
                print(f"开放时间数据文件不存在: {self.open_hours_path}")
                return None
            
            with open(self.open_hours_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            return data
        except Exception as e:
            print(f"加载开放时间数据失败: {e}")
            return None
    
    def get_today_open_hours(self):
        """获取今天的开放时间"""
        # 中文星期映射
        weekdays_zh = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        today_index = datetime.now().weekday()  # 0-6，0表示周一
        today_zh = weekdays_zh[today_index]
        
        data = self.load_open_hours()
        if data and 'open_hours' in data:
            return data['open_hours'].get(today_zh, None)
        return None
    
    def is_field_open_now(self):
        """检查操场现在是否开放"""
        today_hours = self.get_today_open_hours()
        if not today_hours or 'time_slots' not in today_hours:
            return False
        
        current_time = datetime.now().time()
        
        for slot in today_hours['time_slots']:
            try:
                start_time = datetime.strptime(slot['start'], '%H:%M').time()
                end_time = datetime.strptime(slot['end'], '%H:%M').time()
                
                if start_time <= current_time <= end_time:
                    return True
            except ValueError as e:
                print(f"时间格式错误: {e}")
                continue
        
        return False
    
    def load_routes(self):
        """加载跑步路线数据"""
        try:
            if not os.path.exists(self.routes_path):
                print(f"跑步路线数据文件不存在: {self.routes_path}")
                return self._get_default_routes()
            
            with open(self.routes_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            return data
        except Exception as e:
            print(f"加载跑步路线数据失败: {e}")
            return self._get_default_routes()
    
    def _get_default_routes(self):
        """获取默认的跑步路线数据"""
        return [
            {
                "id": 1,
                "name": "校园内环",
                "distance": 2.5,  # 公里
                "elevation_gain": 50,  # 米
                "difficulty": "简单",
                "description": "围绕校园主干道的平坦路线，适合日常训练",
                "path": [
                    {"lat": 39.9042, "lng": 116.4074},  # 示例坐标，实际应替换为校园坐标
                    {"lat": 39.9052, "lng": 116.4084},
                    {"lat": 39.9062, "lng": 116.4074},
                    {"lat": 39.9052, "lng": 116.4064}
                ]
            },
            {
                "id": 2,
                "name": "操场跑道",
                "distance": 0.4,  # 标准400米跑道
                "elevation_gain": 0,
                "difficulty": "简单",
                "description": "标准田径场跑道，全天候开放",
                "path": [
                    {"lat": 39.9045, "lng": 116.4078},
                    {"lat": 39.9047, "lng": 116.4082},
                    {"lat": 39.9045, "lng": 116.4086},
                    {"lat": 39.9043, "lng": 116.4082}
                ]
            },
            {
                "id": 3,
                "name": "后山路线",
                "distance": 5.0,
                "elevation_gain": 150,
                "difficulty": "中等",
                "description": "包含山地路段，有一定坡度，适合提升训练",
                "path": [
                    {"lat": 39.9050, "lng": 116.4070},
                    {"lat": 39.9070, "lng": 116.4090},
                    {"lat": 39.9090, "lng": 116.4070},
                    {"lat": 39.9070, "lng": 116.4050}
                ]
            }
        ]
    
    def save_routes(self, routes_data):
        """保存跑步路线数据"""
        try:
            with open(self.routes_path, 'w', encoding='utf-8') as f:
                json.dump(routes_data, f, ensure_ascii=False, indent=2)
            print(f"跑步路线数据已保存至: {self.routes_path}")
            return True
        except Exception as e:
            print(f"保存跑步路线数据失败: {e}")
            return False
    
    def get_recommended_route(self, difficulty=None):
        """获取推荐的跑步路线"""
        routes = self.load_routes()
        
        if difficulty:
            # 根据难度筛选
            filtered = [r for r in routes if r.get('difficulty', '') == difficulty]
            return filtered[0] if filtered else routes[0] if routes else None
        
        # 默认返回第一条路线
        return routes[0] if routes else None


if __name__ == "__main__":
    # 示例使用
    handler = DataHandler()
    
    # 获取今天开放时间
    today_hours = handler.get_today_open_hours()
    print(f"今日开放时间: {today_hours}")
    
    # 检查是否开放
    is_open = handler.is_field_open_now()
    print(f"操场现在{'开放' if is_open else '未开放'}")
    
    # 获取推荐路线
    route = handler.get_recommended_route()
    print(f"推荐路线: {route['name']}, 距离: {route['distance']}km")